package ikudyk.university;

import java.io.IOException;

public class Operator {
    private char symbol;
    private int operandQuantity;
    private int operandTokenType;
    private int priority;
    private boolean isRightAssociative;

    public Operator(char symbol, int operandQuantity, int operandTokenType,
                    int priority, boolean isRightAssociative) {
        this.symbol = symbol;
        this.operandQuantity = operandQuantity;
        this.operandTokenType = getOperandTokenType();
        this.priority = priority;
        this.isRightAssociative = isRightAssociative;
    }

    static Operator[] operators = Utils.getOperators();

    static Operator getOperatorBySymbol(char symbol) throws IOException {
        if(operators == null) {
            Utils.initOperators();
        }
        for(int i = 0; i < operators.length; i++) {
            if(operators[i].getSymbol() == symbol) {
                return operators[i];
            }
        }
        return null;
    }

    static Operator getOperatorByString(String symbol) throws IOException {
        if(operators == null) {
            Utils.initOperators();
        }
        if(symbol.length() != 1) {
            return null;
        }
        char symbolChar = symbol.charAt(0);
        for(int i = 0; i < operators.length; i++) {
            if(operators[i].getSymbol() == symbolChar) {
                return operators[i];
            }
        }
        return null;
    }

    public int getOperandTokenType() { return operandTokenType; }

    public char getSymbol() {
        return symbol;
    }

    public int getOperandQuantity() {
        return operandQuantity;
    }

    public int getPriority() {
        return priority;
    }

    public boolean isRightAssociative() {
        return isRightAssociative;
    }

    public static boolean areOperatorsEqual(Operator op1, Operator op2) {
        if(op1.getSymbol() == op1.getSymbol()
                && op1.getOperandQuantity() == op2.getOperandQuantity()
                && op1.isRightAssociative() == op2.isRightAssociative()
                && op1.getOperandTokenType() == op2.getOperandTokenType()
                && op1.getPriority() == op1.getPriority()) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean changeToUnaryPlusMinus(Operator plusMinus, int priority) {
        if(plusMinus.getOperandQuantity() == 2) {
            if(plusMinus.getSymbol() == '+') {
                plusMinus = new Operator('P', 1, plusMinus.getOperandTokenType(), plusMinus.getPriority(), true);
                return true;
            } else if(plusMinus.getSymbol() == '-') {
                plusMinus = new Operator('M', 1, plusMinus.getOperandTokenType(), plusMinus.getPriority(), true);
                return true;
            }
        }
        return false;
    }

}
